#!/bin/bash -e

LINUX_KERN_DIR=orangepi_h3_linux/OrangePi-Kernel/linux-3.4.112
LINUX_MOD_DIR=$LINUX_KERN_DIR/out-put/lib/modules
ANDROID_OUT_DIR=out/sun8iw7p1/android/common
ANDROID_MOD_DIR=$ANDROID_OUT_DIR/lib/modules/3.4.39
CROSS_COMPILE=
BSP_DIR=android4.4.2-opi-pcplus-bsp

cd ..
WORK_DIR=`pwd`

TMP_FILE=`find $LINUX_MOD_DIR -name mali.ko`
if [ -z $TMP_FILE ]; then
    echo "gpu is not compiled, compile it now"
    mkdir -p $LINUX_MOD_DIR/kernel/driver/gpu/mali
    cd $LINUX_KERN_DIR/modules/mali
    make ARCH=arm CROSS_COMPILE=$CROSS_COMPILE LICHEE_KDIR=$LINUX_KERN_DIR LICHEE_MOD_DIR=$LINUX_MOD_DIR
    if [ $? ne 0 ]; then
        echo "gpu compile fail."
        exit -1
    else
        echo "gpu compile suceess."
    fi
fi

cd WORK_DIR

TMP_FILE=`find $LINUX_MOD_DIR -name nand.ko`
if [ -z $TMP_FILE ]; then
    echo "nand is not compiled, compile it now"
    cd $LINUX_KERN_DIR/modules/nand
    make ARCH=arm CROSS_COMPILE=$CROSS_COMPILE LICHEE_KDIR=$LINUX_KERN_DIR LICHEE_MOD_DIR=$LINUX_MOD_DIR
    if [ $? ne 0 ]; then
        echo "nand compile fail"
        exit -1
    else 
        TMP_FILE=`find -name nand.ko`
        cp $TMP_FILE $LINUX_MOD_DIR
        echo "nand compile success"
    fi
fi

cd WORK_DIR
mkdir -p $ANDROID_MOD_DIR

echo "replacing the linux kernel and modules..."
cp $LINUX_KERN_DIR/arch/arm/boot/Image $ANDROID_OUT_DIR/bImage
echo "    kernel replaced."

for file in `find $LINUX_MOD_DIR -name *.ko`; do
    cp $file $ANDROID_MOD_DIR/
done
echo "    modules replaced."
echo "patching the android source..."
echo "    backing up the files ..."

if [ ! -d backup ]; then
	mkdir -p backup/android/device/softwinner/dolphin-fvd-p1
	mv android/device/softwinner/dolphin-fvd-p1/{BoardConfig.mk,init.rc} backup/android/device/softwinner/dolphin-fvd-p1

	# patch opi-pc+ wifi hal driver: rtl8189fs
	mkdir -p backup/android/hardware/libhardware_legacy/wifi
	mv android/hardware/libhardware_legacy/wifi/{Android.mk,wifi.c} backup/android/hardware/libhardware_legacy/wifi
fi

if [ ! -d $BSP_DIR ]; then
echo -n "    checking out the new source..."
	git clone https://git.oschina.net/seth_yang/android4.4.2-opi-pcplus-bsp.git $BSP_DIR
	if [ $? ne 0 ]; then
		echo "checkout fail."
		exit -1
	else
		echo " done"
	fi
fi

cp $BSP_DIR/android/device/softwinner/dolphin-fvd-p1/{BoardConfig.mk,init.rc} android/device/softwinner/dolphin-fvd-p1/
# patch opi-pc+ wifi hal driver: rtl8189fs
cp $BSP_DIR/android/hardware/libhardware_legacy/wifi/{Android.mk,wifi.c} android/hardware/libhardware_legacy/wifi

cd ../android
echo "now you can make android as usually"
echo
